const { successModel, errorModel, lackModel, notLoginModel } = require("../utils/resModel");
const checkData = require("../utils/checkData");
const { tokenToInfo } = require("../controller/userController");
const { addInfo, getInfo, updateInfo,delInfo} = require("../controller/appointmentController");
const qr = require("qr-image");
const fs = require('fs');
const path = require('path');

const appointmentRouter = async (req, res) => {
      /**
     * 
     * @api {POST} api/appointment/addInfo 添加预约信息
     * @apiName 添加预约信息
     * @apiGroup appointment
     * @apiVersion  1.0.0
     * 
     * 
     * @apiParam  {String} sessionsId sessionsID
     * @apiParam  {String} sessionsTime sessionsTime
     * @apiParam  {String} token token
     * 
     * 
     * @apiParamExample  {type} Request-Example:
     * {
     *     sessionsId : '11',
     *     sessionsTime : '1605070800000',
     *     token : '123456789123456789'
     * }
     * 
     * 
     * @apiSuccessExample {type} Success-Response:
     * {
     *     msg : "成功新增预约";
     * }
     * 
     * 
     */
    if (req.method === "POST" && req.path === "/api/appointment/addInfo") {
        console.log(req.body);
        // return (successModel({ data: [{}, {}, {}], msg: "成功新增预约" }))
        let checkRes = checkData(req, "sessionId", "sessionTime", "token");
        if (typeof checkRes === "boolean") {
            //判断用户是否有预约，token是否正确
            let userInfo = await tokenToInfo(req.body);
            if (userInfo.length) {
                if (userInfo[0].is_appointment) {
                    // 已经预约的状态
                    return errorModel("该用户已预约");
                } else {
                    // 生成二维码   
                    let qrInfo = qr.image("http://book.0melon0.cn");
                    let fileName = `${Date.now()}.png`
                    let qrcodePath = path.join(__dirname, "../qrcode", fileName);
                    qrInfo.pipe(require("fs").createWriteStream(qrcodePath));
                    // req.body.qrcode = encodeURI("http:\/\/" + path.join(req.headers.host, 'src', 'qrcode', fileName));
                    req.body.qrcode = encodeURI("http:\/\/" + path.join('flowernode.bestlauminer.vip', 'src', 'qrcode', fileName));
                    // 下一步,更新数据
                    let appointmentRes = await addInfo(req.body);
                    if (appointmentRes['changedRows']) {
                        return successModel("成功预约")
                    } else {
                        return errorModel("预约失败，请重新尝试")
                    }
                }
            } else {
                // 未登录
                return notLoginModel();
            }
        } else {
            return lackModel(`${checkRes}参数格式不正确`);
        }
    }

     /**
     * 
     * @api {GET} api/appointment/getInfo 获取预约
     * @apiName 获取预约
     * @apiGroup appointment
     * @apiVersion  1.0.0
     * 
     * 
     * @apiParam  {String} token token值
     * 
     *
     * @apiParamExample  {type} Request-Example:
     * {
     *    token : e2813800c58807182c35dd1ca19d49f01606275134700
     * }
     * 
     * 
     * @apiSuccessExample {type} Success-Response:
     * {
     *     {
     *  "name": "s",
     *  "session_time": null,
     *  "qrcode": null
     *      }
     * }
     * 
     * 
     */
    if (req.method === "GET" && req.path === "/api/appointment/getInfo") {
        // return (successModel({ data: [{}, {}, {}], msg: "成功获取预约信息" }))
        let checkRes = checkData(req, "token");
        if (typeof checkRes === "boolean") {
            let appointmentRes= await getInfo(req.query);
                return successModel(appointmentRes);
        }else{
            return lackModel(`${checkRes}参数格式不正确`);
        }
    }

    /**
     * 修改预约信息
     */
    if (req.method === "PUT" && req.path === "/api/appointment/updateInfo") {
        // return (successModel({ data: [{}, {}, {}], msg: "成功修改预约信息" }))
        let checkRes = checkData(req, "token");;
        if (typeof checkRes === "boolean") {
            let appointmentRes= await updateInfo(req.body);
            if (appointmentRes['changedRows']) {
                return successModel("成功修改");
            }else{ 
                return errorModel("修改失败") 
            }
        }else{
            return lackModel(`${checkRes}参数格式不正确`);
        }
    }

     /**
     * 
     * @api {DELETE} api/appointment/delInfo 取消预约信息
     * @apiName 取消预约信息
     * @apiGroup appointment
     * @apiVersion  1.0.0
     * 
     * 
     * @apiParam  {String} token token值
     * 
     * 
     * @apiParamExample  {type} Request-Example:
     * {
     *     token:"c356034e43e65119b5b937654cedfe7a1604916889014"
     * }
     * 
     * 
     * @apiSuccessExample {type} Success-Response:
     * {
     *     msg: "成功取消预约";
     * }
     * 
     * 
     */
    if (req.method === "DELETE" && req.path === "/api/appointment/delInfo") {
        let checkRes = checkData(req, "token");
        if (typeof checkRes === "boolean"){
            let appointmentRes = await delInfo(req.body);

            if (appointmentRes['changedRows']) {
                return successModel("修改成功")
            } else {
                return errorModel("修改失败")
            }
        } else {
            return lackModel(`${checkRes}参数格式不正确`);
        }
    }
}
module.exports = appointmentRouter;